package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.context.BaseContext;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class Orderservicelmpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 订单支付
     *
     * @param ordernum
     * @return
     */
    public boolean payment(String ordernum) throws Exception {
        // 当前登录用户id
        boolean updatestatus = this.update().eq("number", ordernum).set("status", 2).update();
        log.info("update is {}",updatestatus);
        return updatestatus;

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = userMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        userMapper.update(orders);
        //提醒前端 来单提醒
        //约定需要这三个参数type orderid content 前端需要解析这三个参数
        HashMap<Object, Object> map = new HashMap<>();
        map.put("type",1);//type为1代表来单提醒
        map.put("orderid",ordersDB.getId());//订单id
        map.put("content","订单号"+ordersDB.getNumber());//订单号
        //将map转为json字符串
        String s = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(s);
    }

    @Override
    public List<Orders> historybyuser() {
        List<Orders> orders = this.query().eq("user_id", BaseContext.getCurrentId()).list();
        return orders;
    }


}
